﻿using System;
using System.Linq;
using db = DataContext;

namespace WebApplication.admin
{
	public partial class NewsType : System.Web.UI.Page
	{
		public int id;

		protected void Page_Load(object sender, EventArgs e)
		{
			Common.CheckLogin();

			id = Common.Id;
			db.NewsType type;

			using (db.DbDataContext context = new db.DbDataContext())
			{
				if (Common.IsEdit)
				{
					type = context.NewsType.Single(x => x.Id == id);
					name.Value = type.Name;
					sort.Value = type.Sort.ToString();

					btn_save.Value = "保存";
					lit_action.Text = "编辑";
				}

				if (Common.IsSave)
				{
					if (id > 0)
					{
						type = context.NewsType.Single(x => x.Id == id);
						type.Name = Request.Form["name"];
						type.Sort = int.Parse("0" + Request.Form["sort"]);
						context.SubmitChanges();
					} else
					{
						context.NewsType.InsertOnSubmit(new db.NewsType
						{
							Name = Request.Form["name"],
							Sort = int.Parse("0" + Request.Form["sort"])
						});
						context.SubmitChanges();
					}
					Response.Redirect("news_types.aspx", true);
				}

				if (Common.IsDelete)
				{
					type = context.NewsType.Single(x => x.Id == id);
					if (type.News.Count > 0)
					{
						msg.InnerText = "类别【" + type.Name + "】中还有新闻，不能删除该分类。";
					} else
					{
						context.NewsType.DeleteOnSubmit(type);
						context.SubmitChanges();
						Response.Redirect("news_types.aspx", true);
					}
				}

				t_list.DataSource = context.NewsType;
				t_list.DataBind();
			}
		}
	}
}